package com.metagurukul.metaspace.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.metagurukul.metaspace.models.beans.Role;
import com.metagurukul.metaspace.util.Constants;

/**
 * @author ritesh gupta
 * this class is for manage roles
 *
 */
public class RoleDao extends DatabaseDAO{
	/**to get all roles stored in the database
	 * @return list of roles
	 * @throws SQLException
	 */
	public List<Role> getRecordList ()
	throws SQLException {
		ArrayList<Role> roleList = null;
		String query = "Select * from Role";
		try {
			getConnection();
			ps = con.prepareStatement(query);
			rs = ps.executeQuery();
			roleList = new ArrayList<Role>();
			while (rs.next()) {
				Role role = new Role();
				role.setRoleId(rs.getInt("role_id"));
				role.setRoleName(rs.getString("role_name"));
				roleList.add(role);
			}
		} catch (SQLException e) {
			throw new SQLException(Constants.SQL_QUERY_ERROR + e);
		} finally {
			/* close connection */
			closeConnection();
		}
		return roleList;
		
	}
	
	/**to get name of role when a roleid is given
	 * @param roleId id of role
	 * @return name of role
	 * @throws SQLException
	 */
	public String getName(int roleId) throws SQLException{
		String query = "Select role_name from Role where role_id = ?";
		try {
			getConnection();
			ps = con.prepareStatement(query);
			ps.setInt(1, roleId);
			rs = ps.executeQuery();
			if (rs.next()) {
				return rs.getString("role_name");
			}
		} catch (SQLException e) {
			throw new SQLException(Constants.SQL_QUERY_ERROR  + e);
		} finally {
			/* close connection */
			closeConnection();
		}
		return null;
	}
	
}
